package com.huawei.chengdu.meetingdemo.view.dialogs;

import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.huawei.chengdu.meetingdemo.R;
import com.huawei.chengdu.meetingdemo.consts.ObserverConts;
import com.huawei.chengdu.meetingdemo.consts.ViewNameConts;
import com.huawei.chengdu.meetingdemo.presenter.ConfSdkPresenter;
import com.huawei.chengdu.meetingdemo.util.LogUtil;
import com.huawei.chengdu.meetingdemo.view.IViewDataObserver;
import com.huawei.chengdu.meetingdemo.presenter.MeetingManager;

import java.util.HashMap;
import java.util.Map;

/**
 * Author: xurui 30031276
 * Created on 2022/10/9 11:31
 * Desc：更多弹窗
 */
public class MeetingSettingDialog extends FloatWindowBase implements IViewDataObserver {
    private static final String TAG = MeetingSettingDialog.class.getSimpleName();

    /**
     * 申请主席view
     */
    public static final String ADV_APPLY_HOST_VIEW = "adv_appply_host_view";

    /**
     * 延长会议view
     */
    public static final String EXTEND_MEETING_SETTINGS_VIEW = "extend_meeting_settings_view";

    /**
     * 会议信息
     */
    public static final String CONF_INFO_VIEW = "adv_conf_info_view";

    /**
     * 会议信息--高级
     */
    public static final String ADV_CONF_INFO_VIEW = "adv_meeting_info_view";

    /**
     * 其他
     */
    public static final String CONF_OTHER_VIEW = "conf_other_view";

    //全屏的Layout，用于显示设置、配置向导等界面。
    private FrameLayout fullScreenLayout;
    //申请主席
    private RelativeLayout hostLin;
    private TextView hostTagTv;
    //延长会议
    private RelativeLayout rlItemConfExtend;
    //会议信息
    private RelativeLayout rlItemConfInfo;
    //延长会议和申请主席的view
    private View llHostCtrlPad;

    private final Map<String, ViewGroup> relativeLayouts = new HashMap<>();
    //关闭按钮
    private ImageView ivClose;

    public MeetingSettingDialog(@NonNull Context context, int posX, int posY) {
        super(context);
        super.addSecureFlag();
        int xCoordinate = (int) mContext.getResources().getDimension(R.dimen.def_dimens_960);
        int yCoordinate = (int) mContext.getResources().getDimension(R.dimen.def_dimens_400);
        LogUtil.debug(TAG + " posX:" + posX + ", posY:" + posY);
        LogUtil.debug(TAG + " xCoordinate:" + xCoordinate + ", yCoordinate:" + yCoordinate);
        super.setWmPositionParams(Gravity.BOTTOM | Gravity.START, xCoordinate, yCoordinate,
                 ViewGroup.LayoutParams.WRAP_CONTENT,
                (int) mContext.getResources().getDimension(R.dimen.def_dimens_1484));
        dlgWidth = ViewGroup.LayoutParams.WRAP_CONTENT;
        dlgHeight = ViewGroup.LayoutParams.MATCH_PARENT;
        initView();
        initEvent();
        // 首先显示会议信息
        showConfInfoView();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.meeting_settings;
    }

    @Override
    protected String getChildName() {
        return TAG;
    }

    /**
     * 显示悬浮窗
     */
    @Override
    public void showFloatWindow() {
        LogUtil.info("showFloatWindow");
        super.showFloatWindow();
        registerListenerService();
        super.sendRectBroadCast(true, TAG);
    }

    /**
     * 释放资源
     */
    @Override
    public void release() {
        LogUtil.info("release");
        unRegisterListenService();
        super.release();
        super.sendRectBroadCast(false, TAG);
        destroysView();
    }
    private void destroysView() {
        LogUtil.info("destroysView()");
        ViewsFactory.getInstance().removeView(ViewNameConts.ADV_APPLY_HOST_VIEW);
        ViewsFactory.getInstance().removeView(ViewNameConts.EXTEND_MEETING_SETTINGS_VIEW);
        ViewsFactory.getInstance().removeView(ViewNameConts.CONF_INFO_VIEW);
        ViewsFactory.getInstance().removeView(ViewNameConts.ADV_CONF_INFO_VIEW);
        ViewsFactory.getInstance().removeView(ViewNameConts.CONF_OTHER_VIEW);
    }

    private void initView() {
        fullScreenLayout = mRootView.findViewById(R.id.fullScreenLayout);
        rlItemConfInfo = mRootView.findViewById(R.id.rl_item_conf_info);
        hostLin = mRootView.findViewById(R.id.host_lin);
        hostTagTv = mRootView.findViewById(R.id.host_tag_tv);
        rlItemConfExtend = mRootView.findViewById(R.id.rl_item_conf_extend);
        ivClose = mRootView.findViewById(R.id.iv_close);
        llHostCtrlPad = mRootView.findViewById(R.id.host_ctrl_pad);
        initRelativeLayouts();
        //点对点会议和非视频会议判断 是否展示申请主席&延长会议
        if (MeetingManager.getInstance().isJoinConfStateP2P()) {
            hostLin.setVisibility(View.GONE);
            rlItemConfExtend.setVisibility(View.GONE);
            llHostCtrlPad.setVisibility(View.GONE);
        }
        //如果是主席，显示释放主席；反之，申请主席
        hostTagTv.setText(ConfSdkPresenter.isChairman()
                ? mContext.getResources().getText(R.string.host_release)
                : mContext.getResources().getText(R.string.host_claim));
    }

    /**
     * 顺序添加键值对
     */
    private void initRelativeLayouts() {
        relativeLayouts.clear();
        relativeLayouts.put(ADV_APPLY_HOST_VIEW, hostLin);
        relativeLayouts.put(EXTEND_MEETING_SETTINGS_VIEW, rlItemConfExtend);
        relativeLayouts.put(CONF_INFO_VIEW, rlItemConfInfo);
    }

    /**
     * 更多点击项
     */
    private void initEvent() {
        rlItemConfInfo.setOnClickListener(view -> showConfInfoView());
        hostLin.setOnClickListener(view -> showAdvApplyHostView());
        rlItemConfExtend.setOnClickListener(view -> showExtendViewMeetingSettings());
        ivClose.setOnClickListener((view -> release()));
    }

    private void showAdvApplyHostView() {
        unRegisterInnerListen();
        if (ViewsFactory.getInstance().isViewExist(ViewNameConts.ADV_APPLY_HOST_VIEW)) {
            ViewsFactory.getInstance().removeView(ViewNameConts.ADV_APPLY_HOST_VIEW);
        }
        BaseView baseView = ViewsFactory.getInstance().getBaseView(mContext, ViewNameConts.ADV_APPLY_HOST_VIEW, true);
        if (baseView instanceof AdvApplyHostView) {
            AdvApplyHostView applyHostView = (AdvApplyHostView) baseView;
            applyHostView.setOnDialogDismissEvent(this::release);
            applyHostView.setUpdateParentViewItemEvent(hostTagTv::setText);
            applyHostView.setFromView(ViewNameConts.ADV_APPLY_HOST_VIEW);
            loadFullWorkArea(applyHostView);
            refreshUIFromPos(ViewNameConts.ADV_APPLY_HOST_VIEW);
        }
    }

    private void unRegisterInnerListen() {
        BaseView baseView = ViewsFactory.getInstance().getBaseView(mContext, ViewNameConts.ADV_APPLY_HOST_VIEW, true);
        if (baseView instanceof AdvApplyHostView) {
            AdvApplyHostView advApplyHostView = (AdvApplyHostView) baseView;
            advApplyHostView.unRegisterListenService();
        }
    }

    private void showExtendViewMeetingSettings() {
        if (ViewsFactory.getInstance().isViewExist(ViewNameConts.EXTEND_MEETING_SETTINGS_VIEW)) {
            ViewsFactory.getInstance().removeView(ViewNameConts.EXTEND_MEETING_SETTINGS_VIEW);
        }
        if (MeetingManager.getInstance().isMeChairman()) {
            BaseView baseView = ViewsFactory.getInstance()
                    .getBaseView(mContext, ViewNameConts.EXTEND_MEETING_SETTINGS_VIEW, true);
            if (baseView instanceof ExtendViewMeetingSettings) {
                ExtendViewMeetingSettings meetingSettings = (ExtendViewMeetingSettings) baseView;
                meetingSettings.setOnDialogDismissEvent(this::release);
                loadFullWorkArea(meetingSettings);
                refreshUIFromPos(ViewNameConts.EXTEND_MEETING_SETTINGS_VIEW);
            }
        } else {
            Toast.makeText(mContext, mContext.getResources().getString(R.string.extend_conf_need_be_chairman), Toast.LENGTH_SHORT).show();
        }
    }

    private void showConfInfoView() {
        unRegisterInnerListen();
        if (ViewsFactory.getInstance().isViewExist(ViewNameConts.CONF_INFO_VIEW)) {
            ViewsFactory.getInstance().removeView(ViewNameConts.CONF_INFO_VIEW);
        }
        BaseView baseView = ViewsFactory.getInstance().getBaseView(mContext, ViewNameConts.CONF_INFO_VIEW, true);
        if (baseView instanceof MeetingInfoView) {
            loadFullWorkArea(baseView);
            refreshUIFromPos(ViewNameConts.CONF_INFO_VIEW);
        }
    }

    /*
     * 根据当前点击选中的位置刷新dialog界面
     */
    private void refreshUIFromPos(String viewName) {
        for (Map.Entry<String, ViewGroup> entry : relativeLayouts.entrySet()) {
            if (entry.getKey().equals(viewName)) {
                entry.getValue().setBackground(mContext.getDrawable(R.drawable.more_resource_dialog_select));
            } else {
                entry.getValue().setBackground(null);
            }
        }
    }

    /**
     * 加载全屏的Layout，主要用于设置、配置向导、结束会议、摄像机控制等界面。
     *
     * @param view 需要被加载的设置中的view
     */
    public void loadFullWorkArea(BaseView view) {
        if (view == null) {
            return;
        }
        fullScreenLayout.setVisibility(View.VISIBLE);
        fullScreenLayout.removeAllViews();
        fullScreenLayout.addView(view.getLayoutView());
    }

    @Override
    public void viewDataChanged(int eventId, Object obj) {
        LogUtil.info(TAG + " viewDataChanged , eventId : " + eventId);
        if (eventId == ObserverConts.MSG_ATTENDESS_CHANGE_STATUS) {
            hostTagTv.setText(MeetingManager.getInstance().isMeChairman()
                    ? mContext.getResources().getText(R.string.host_release)
                    : mContext.getResources().getText(R.string.host_claim));
        }
    }

    @Override
    public void unRegisterListenService() {
        LogUtil.info(TAG + " MeetingSettingDialog unRegisterListenService");
        MeetingManager.getInstance().unregistDataChangeListenerObj(this);
    }

    @Override
    public void registerListenerService() {
        LogUtil.info(TAG + " MeetingSettingDialog registerListenerService");
        MeetingManager.getInstance().registerObserved(ObserverConts.MSG_ATTENDESS_CHANGE_STATUS, this);
    }
}
